<template>
  <div>
    <el-form :inline="true" :model="form" class="demo-form-inline">
      <el-form-item label="关键词:">
        <el-input v-model="form.keyword" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="领域:">
        <el-select v-model="form.field" multiple placeholder="请选择">
          <el-option
            v-for="item in video_search_index.field"
            :label="item"
            :value="item"
            :key="item"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="get_manage_video_list"
          >查询</el-button
        >
        <el-button type="warning" @click="add">新增</el-button>
      </el-form-item>
    </el-form>

    <el-table :data="video_list" border stripe style="width: 100%">
      <el-table-column type="index" width="50" label="序号" />
      <el-table-column prop="title" label="展示图片" width="125">
        <template #default="scope">
          <el-image
            v-if="scope.row.header_img"
            style="width: 100px; height: 100px"
            :src="scope.row.header_img"
            :zoom-rate="1.2"
            :max-scale="7"
            :min-scale="0.2"
            :preview-src-list="[scope.row.header_img]"
            :initial-index="4"
          />
          <img
            v-else
            class="w-100px w-100px"
            src="@/assets/images/moren_.jpg"
            alt=""
          />
        </template>
      </el-table-column>
      <el-table-column prop="title" label="名称" />
      <el-table-column prop="teacher" label="讲师" width="120" />
      <el-table-column prop="field" label="领域" width="120" />
      <el-table-column prop="source" label="来源" />
      <el-table-column prop="ctime" label="上传时间" />
      <el-table-column prop="title" label="操作" width="120">
        <template #default="scope">
          <el-button link type="primary" size="small" @click="edit(scope.row)"
            >修改</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-if="list_total !== 0"
      class="my-30px flex flex-justify-center flex-items-center"
      background
      layout="prev, pager, next"
      :total="list_total"
      :page-size="form.page_size"
      @current-change="handleCurrentChange"
    />

    <el-dialog v-model="add_show" title="视频信息" width="500">
      <el-form :inline="true" :model="video_form" class="demo-form-inline">
        <el-form-item label="名称:">
          <el-input v-model="video_form.title" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="展示头图:">
          <div>
            <img src="" alt="" />
            <el-upload
              v-model:file-list="imgList"
              accept=".png, .jpg, .jpeg"
              class="mt-20px"
              :before-upload="beforeUpload"
              :on-remove="handleRemove"
              list-type="picture"
            >
              <el-button type="primary">点击上传图片</el-button>
            </el-upload>
          </div>
        </el-form-item>
        <el-form-item label="视频类型:">
          <el-input v-model="video_form.type" placeholder="请输入" />
        </el-form-item>

        <el-form-item label="领域:">
          <el-select v-model="video_form.field" multiple placeholder="请选择">
            <el-option
              v-for="item in video_search_index.field"
              :label="item"
              :value="item"
              :key="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="关键词:">
          <el-input
            v-model="video_form.keyword"
            placeholder="多个关键词请用,分隔"
          />
        </el-form-item>
        <el-form-item label="内容描述:">
          <el-input v-model="video_form.content" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="来源:">
          <el-input v-model="video_form.source" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="讲师:">
          <el-select v-model="video_form.teacher" placeholder="请选择">
            <el-option
              v-for="item in video_search_index.teacher"
              :label="item.name"
              :value="item.name"
              :key="item.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="视频文件名称:">
          <el-input v-model="video_form.file_name" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="视频级别:">
          <el-select v-model="video_form.level" placeholder="请选择">
            <el-option
              v-for="item in level_list"
              :label="item.label"
              :value="item.value"
              :key="item.label"
            />
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="add_video"> 提交 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from "vue";
import {
  update_video_info,
  manage_video_list,
  add_video_info,
  video_index,
} from "@/api/index";
import { ElMessage } from "element-plus";
import * as imageConversion from "image-conversion";

const list_total = ref(0);
const type = ref("");
const video_list = ref([]);
const imgList = ref([]);
let video_form = reactive({
  title: "",
  header_img: "",
  type: "",
  field: [],
  keyword: "",
  hours: "1",
  content: "",
  source: "",
  teacher: "",
  file_name: "",
  level: "",
});
const add_show = ref(false);
let form = reactive({
  keyword: "",
  type: "",
  page: 1,
  page_size: 5,
  field: [],
  teacher: "",
});
const level_list = [
  { label: "免费观看", value: 1 },
  { label: "需会员或购买才能观看", value: 2 },
];
const video_search_index = ref({});

// 分页处理
const handleCurrentChange = (val) => {
  form.page = val;
  get_manage_video_list();
};
const add = () => {
  add_show.value = true;
  type.value = "add";
};
const edit = (data) => {
  type.value = "edit";
  add_show.value = true;
  for (const key in data) {
    video_form[key] = data[key];
  }
  video_form.header_img = data.header_img;
  video_form.field = data.field.split(",");
  const obj = {
    train: "培训",
  };
  video_form.type = obj[data.type];
  imgList.value = [{ name: "封面图片", url: data.header_img }];
};

const get_manage_video_list = async () => {
  const {
    data: { data, total },
  } = await manage_video_list({ ...form, field: form.field.join(",") });
  video_list.value = data;
  list_total.value = total;
};
get_manage_video_list();

const get_video_index = async () => {
  const { data } = await video_index();
  video_search_index.value = data;
};
get_video_index();

const add_video = async () => {
  if (type.value === "add") {
    const { data, code } = await add_video_info({
      ...video_form,
      field: video_form.field.join(","),
    });
    if (code === 200) ElMessage.success("新增成功");
    ElMessage.error("新增失败！");
  } else {
    submit_edit();
  }
};

const submit_edit = async () => {
  const { data, code } = await update_video_info({
    ...video_form,
    field: video_form.field.join(","),
  });
  if (code === 200) {
    ElMessage.success("修改成功");
    get_manage_video_list();
  } else {
    ElMessage.error("修改失败！");
  }
  add_show.value = false;
};

const beforeUpload = (file) => {
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    ElMessage.error("上传图片大小不能超过2MB");
    return false;
  } else {
    const isSize = new Promise((resolve, reject) => {
      const _URL = window.URL || window.webkitURL;
      const img = new Image();
      img.onload = () => {
        const valid = true;
        valid ? resolve() : reject();
      };
      img.src = _URL.createObjectURL(file);
    }).then(
      () => {
        return file;
      },
      () => {
        ElMessage.error("上传图片大小不能超过2MB");
        return Promise.reject();
      }
    );
    isSize.then((file) => {
      const isJpgOrPng =
        file.type === "image/jpeg" || file.type === "image/png";
      const isLt2M = file.size / 1024 < 100;
      if (!isJpgOrPng) {
        ElMessage.error("上传图片只能是 JPG 或 PNG 格式!");
        return false;
      }
      return new Promise((resolve) => {
        // 小于100KB 不压缩
        if (isLt2M) {
          resolve(file);
        }
        // 压缩到200KB,这里的200就是要压缩的大小,可自定义
        imageConversion.compressAccurately(file, 50).then((res: any) => {
          toBase64(res);
          resolve(res);
        });
      });
    });
  }
  return false; //取消自动上传
};

const handleRemove = (file) => {
  imgList.value = [];
  form.header_img = "";
};

const toBase64 = (file) => {
  let reader = new FileReader();
  reader.onloadend = function () {
    imgList.value = [];
    video_form.header_img = reader.result;
    imgList.value.push({ name: "封面图片", url: video_form.header_img });
  };
  if (file) {
    reader.readAsDataURL(file);
  }
};
</script>

<style scoped></style>
